package com.xiaoshuidi.cloud.module.report.service.bigdata;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.xiaoshuidi.cloud.module.report.controller.bigdata.vo.ApartmentIndicatorAnalysisVO;
import com.xiaoshuidi.cloud.module.report.controller.bigdata.vo.ApartmentRevenueVO;
import com.xiaoshuidi.cloud.module.report.dal.mapper.bigdata.IndicatorAnalysisMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@RequiredArgsConstructor
@Service
public class IndicatorAnalysisServiceImpl implements IndicatorAnalysisService {

    private final IndicatorAnalysisMapper indicatorAnalysisMapper;


    @Override
    public ApartmentIndicatorAnalysisVO apartmentRevenueByType(Integer concentrated) {
        List<ApartmentRevenueVO> apartmentRevenueVOS = indicatorAnalysisMapper.apartmentRevenueByType(concentrated);
        ApartmentIndicatorAnalysisVO vo = ApartmentIndicatorAnalysisVO.builder()
                .totalAmount(apartmentRevenueVOS.stream().map(ApartmentRevenueVO::getTotalAmount).reduce(BigDecimal.ZERO, BigDecimal::add))
                .rentAmount(apartmentRevenueVOS.stream().map(ApartmentRevenueVO::getRentAmount).reduce(BigDecimal.ZERO, BigDecimal::add))
                .apartmentRevenueVOList(apartmentRevenueVOS).build();
        if (vo.getTotalAmount().compareTo(BigDecimal.ZERO) != 0) {
            vo.setTotalAmount(vo.getTotalAmount().setScale(2, BigDecimal.ROUND_DOWN));
        }
        if (vo.getRentAmount().compareTo(BigDecimal.ZERO) != 0) {
            vo.setRentAmount(vo.getRentAmount().setScale(2, BigDecimal.ROUND_DOWN));
        }
        return vo;
    }

    @Override
    public BigDecimal revenueByTypeAndTime(Integer concentrated, String time) {
        Date date = null;
        if (StrUtil.isNotBlank(time)) {
            date = DateUtil.parse(time, time.length() == 4 ? "yyyy" : "yyyy-MM-dd");
        }
        BigDecimal bigDecimal = indicatorAnalysisMapper.revenueByTypeAndTime(concentrated, date);
        return bigDecimal.compareTo(BigDecimal.ZERO) != 0 ? bigDecimal.setScale(2, BigDecimal.ROUND_DOWN) : bigDecimal;
    }

}
